home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 7251 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: pegasus.montclair.edu!harmon
  2. From: harmon@pegasus.montclair.edu (Derek Harmon)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Q: pointers to pointers that point to structs?
  5. Date: 10 Feb 1996 04:03:19 -0500
  6. Organization: Montclair State University
  7. Message-ID: <harmon.823942018@pegasus.montclair.edu>
  8. References: <311C1B4E.217F@mars.superlink.net>
  9. NNTP-Posting-Host: pegasus.montclair.edu
  10. X-Newsreader: NN version 6.5.0 #68 (NOV)
  11.  
  12. Michael Rizzo <rizzom@mars.superlink.net> writes:
  13.  
  14. >  I am having trouble dereferencing a pointer to a pointer to a struct.
  15. >For simplicity just say the struct is:
  16. >struct test
  17. >  {
  18. >  char teststr[10];
  19. >  int  testint;
  20. >  }
  21.  
  22. >void f(test **temp)
  23. >{
  24. >printf("%s  %d",(please fill in the blank))
  25. >}
  26.  
  27. : printf("%s  %d", (*temp)->teststr, (*temp)->testint);
  28.  
  29.    And I'll tell you why (and how).  As you are working with a pointer to
  30. a structure, your assertion about requiring -> over . was correct.  Intuitive-
  31. ly you might then extend the idea to ->->, but at that point you will learn
  32. that in C, the token immediately to the left of a -> operator must be a
  33. pointer to a structure (probably thanks to a fine compiler Help system ;) ).
  34.  
  35.    So from **temp, how do we get a pointer?  Well, whereas intptr (just making
  36. this variable up) is a pointer to an int, *intptr is an integer value.  So..
  37. let's call temp testptrptr, for reasons that will be clear in a moment, then
  38. testptrptr is a pointer to a pointer to a test struct.  *testptrptr is a
  39. pointer to a test struct. (!)  **testptrptr is a test struct.  So we want one
  40. asterisk.
  41.  
  42.    Unfortunately (I should say, laid down by the powers that created C), the
  43. order of operator precedence says -> comes before *, so *temp->testint will
  44. not work.  That's where the parenthesis come in handy, and as the above example
  45. shows, (*temp)->testint will produce an integer value.
  46.  
  47.    Recap,
  48.  
  49. >void f(test **temp)
  50.              ^^-- for the first pointer to a struct, always use ->
  51.               \-- for any subsequent pointers, use *, and encircle with ()'s
  52.  
  53.                                                -- Stone
  54. --
  55. # Derek Harmon (aka Stonelight)    harmon@pegasus.montclair.edu
  56. # - Computer Science Undergrad, Montclair State University, NJ
  57. # - My views are my own, nobody else is this creative.  3;)>
  58. ... Eschew obfuscation!
  59.